package finedev.work.vennue;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONObject;

import com.facebook.android.DialogError;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

public class MyActivity extends Activity {
	
	private static final int PICK_FROM_CAMERA = 0;
	private static final int PICK_FROM_ALBUM = 1;
	private static final int CROP_FROM_CAMERA = 2;
	
	private final String TAG = "My";
	
	private Uri mImageCaptureUri;
	public static Bitmap mPhoto;
	
	private Activity mActivity;
	
	private TextView mTextViewName = null;
	private TextView mTextViewLevel = null;
	private TextView mTextViewIncome = null;
	
	private ImageButton mImgBtnProfile;
	private ImageButton mImgBtnFriend;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        
        mActivity = this;
        
        mImgBtnProfile = (ImageButton) findViewById(R.id.my_imgbt_profile);
        mImgBtnFriend = (ImageButton) findViewById(R.id.my_imgbt_friend);
        
        mImgBtnProfile.setOnClickListener( myOnClickListener );
        mImgBtnFriend.setOnClickListener( myOnClickListener );
        
        mTextViewName = (TextView) findViewById( R.id.my_textview_name );
        mTextViewLevel = (TextView) findViewById( R.id.my_textview_level );
        mTextViewIncome = (TextView) findViewById( R.id.my_textview_income );
        
        if ( LoginManager.mHashMapResult != null ) {
        
        	mTextViewName.setText( LoginManager.mHashMapResult.get("user_name") );
        	
        	if ( LoginManager.mHashMapResult.get("access_lv").equals("1") ) {
        		mTextViewLevel.setText("관리자");
        	} else if ( LoginManager.mHashMapResult.get("access_lv").equals("2") ) {
        		mTextViewLevel.setText("광고주");
        	} else if ( LoginManager.mHashMapResult.get("access_lv").equals("3") ) {
        		mTextViewLevel.setText("일반회원");
        	} else if ( LoginManager.mHashMapResult.get("access_lv").equals("4") ) {
        		mTextViewLevel.setText("인증안된회원");
        	}
        	
        } else {
        	mTextViewName.setText( "계정로그인필요" );
        	mTextViewLevel.setText(  "계정로그인필요 " );
        }
        
        String img_path = "data/data/finedev.work.wordrelay/files/profile.png";
		mPhoto = BitmapFactory.decodeFile(img_path);
		if (mPhoto != null)
			mImgBtnProfile.setImageBitmap(mPhoto);
        
        
    }
    
    @Override
    protected void onResume() {
    	
    	Log.i("Friend", "onResume()" );
    	// TODO Auto-generated method stub
    	String img_path = "data/data/finedev.work.vennue/files/profile.png";
		mPhoto = BitmapFactory.decodeFile(img_path);
		if (mPhoto != null)
			mImgBtnProfile.setImageBitmap(mPhoto);
		
    	super.onResume();
    }
    
    private View.OnClickListener myOnClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if ( v.getId() == R.id.my_imgbt_profile ) {
				showDefineProfilePhotoDialog();
			} else if ( v.getId() == R.id.my_imgbt_friend ) {
				if ( BasicInfo.FacebookLogin == true ) {
					BasicInfo.FacebookInstance.setAccessToken( BasicInfo.FACEBOOK_ACCESS_TOKEN );
					Intent changeAcitivityIntent = new Intent( mActivity, FindFriendActivity.class );
					startActivity( changeAcitivityIntent );
				} else {

					BasicInfo.FacebookInstance.authorize( mActivity, new String[] { "email", "read_stream", "publish_stream"},new DialogListener() {
						@Override
						public void onComplete(Bundle values) {
							
							try {
								String resultStr = BasicInfo.FacebookInstance.request("me");
								JSONObject obj = new JSONObject( resultStr );
								
								BasicInfo.FACEBOOK_NAME = obj.getString("name");
								
								BasicInfo.FacebookLogin = true;
								BasicInfo.FACEBOOK_ACCESS_TOKEN = BasicInfo.FacebookInstance.getAccessToken();
								
							} catch ( Exception ex) {
								ex.printStackTrace();
							}
							
							Log.d(TAG, "Authorization completed : " + BasicInfo.FACEBOOK_NAME);
							
							Intent intent = new Intent( mActivity, MainTabActivity.class );
							startActivity( intent );
						}
	
						@Override
						public void onFacebookError(FacebookError error) {
						}
	
						@Override
						public void onError(DialogError e) {
						}
	
						@Override
						public void onCancel() {
						}
					});
				}
//				Intent changeAcitivityIntent = new Intent( mActivity, FindFriendActivity.class );
//				startActivity( changeAcitivityIntent );
			}
		}
	};
	
	private void showDefineProfilePhotoDialog()
	{
		new AlertDialog.Builder( mActivity ).setItems(new String[] { "from camera", "from album" }, new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch( which ) {
				case 0:	// select from camera
					takePhotoFromCamera();
					break;
				case 1:	// select from album
					takePhotoFromAlbum();
					break;
				}
			}
		} ).setNegativeButton("cancle", null).create().show();
	}
	
	private void takePhotoFromCamera()
	{
		Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
		
		String tempUri = "temp_" + String.valueOf( System.currentTimeMillis() ) + ".jpg";
		
		mImageCaptureUri = Uri.fromFile( new File( Environment.getExternalStorageDirectory() , tempUri ) );
		
		intent.putExtra( android.provider.MediaStore.EXTRA_OUTPUT,  mImageCaptureUri );
		
		startActivityForResult( intent, PICK_FROM_CAMERA) ;
		
	}
	
	private void takePhotoFromAlbum()
	{
		Intent intent = new Intent( Intent.ACTION_PICK );
		intent.setType( android.provider.MediaStore.Images.Media.CONTENT_TYPE );
		startActivityForResult(intent, PICK_FROM_ALBUM);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		switch( requestCode ) {
		case CROP_FROM_CAMERA:
			final Bundle extras = data.getExtras();
			
			if ( extras != null ) {
				
				mPhoto = extras.getParcelable("data");
				mImgBtnProfile.setImageBitmap ( mPhoto );
				
				try {
					Log.i("Friend", "store profile image" );
					FileOutputStream fos = openFileOutput("profile.png", 0);
					mPhoto.compress(CompressFormat.PNG, 100, fos);
					fos.flush();
					fos.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
			// delete temp iamge file
			File f = new File( mImageCaptureUri.getPath() );
			if ( f.exists() )
			{
				f.delete();
			}
			
			break;
		case PICK_FROM_ALBUM:
			mImageCaptureUri = data.getData();
			// after action is same as PCK_FROM_CAMERA
			// so missing break;
		case PICK_FROM_CAMERA:
			Intent intent = new Intent( "com.android.camera.action.CROP" );
			intent.setDataAndType( mImageCaptureUri, "image/*");
			
			intent.putExtra("outputX", 90);
			intent.putExtra("outputY", 90);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true );
			intent.putExtra("return-data", true );
			
			startActivityForResult(intent,  CROP_FROM_CAMERA );
			
			break;
		}
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_my, menu);
        return true;
    }
}
